﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：马毅
    //
    // 文件名：HzButton.cs
    // 文件功能描述：带权限的Button 
    // 创建标识：马毅 2009-03-22
    //
    // 修改标识： 
    // 修改描述： 
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
    // 审核时间：
    // 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.Web;
using HZ.DrugTrade.Model;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.Model.Enum;
namespace HZ.DrugTrade.Web.Admin.SystemManage
{
    public partial class CompnayManage : BasePage
    {
        IBLL_Company IBC = Factory.BLL_Company();
        IBLL_User iu = Factory.BLL_User();

        public CompnayManage()
        {
            this.ModuleNo = Module.系统管理.ToString();
            this.PageOperateType = OperateType.企业管理.ToString();
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.IsPostBack)
            {
               
                CompanyBind();

                if (CurrentAccount.GetUser().UserID == "ROOT")
                {
                    //this.hzbtnRandom.Enabled = true;
                    this.hzbtnRandom.Enabled = false;
                    this.hzbtnRandom.Visible = false;

                    this.hzbtnAgree.Enabled = true;
                    this.hzbtnDeny.Enabled = true;
                }
                else
                {
                    this.hzbtnRandom.Enabled = false;
                    this.hzbtnRandom.Visible = false;
                    this.hzbtnAgree.Visible = false;
                    this.hzbtnDeny.Visible = false;
                }
            }
        }

        /// <summary>
        /// 绑定角色列表
        /// </summary>
        private void CompanyBind()
        {

            HZ.DrugTrade.Model.Query.Company ModeComany = new HZ.DrugTrade.Model.Query.Company();
            ModeComany.CompanyID = txtCompanyID.Text.Trim().ToUpper();//注册号
            ModeComany.CompanyName = new HZ.Common.ConvertHelper(txtReturnlName.Text.Trim()).String;
            switch (DllType.SelectedItem.Value.Trim())
            {

                case "0":
                    ModeComany.CompanyType = EnumCompanyType.生产企业;
                    ModeComany.Append = "companytype=0";
                    break;
                case "1":
                    ModeComany.CompanyType = EnumCompanyType.经营企业;
                    ModeComany.Append = "companytype=1";
                    break;
                case "2":
                    ModeComany.CompanyType = EnumCompanyType.配送企业;
                    ModeComany.Append = "companytype=2";
                    break;
                case "3":
                    ModeComany.CompanyType = EnumCompanyType.生产企业直接配送;
                    ModeComany.Append = "companytype=3";
                    break;
                case "4":
                    ModeComany.CompanyType = EnumCompanyType.经营企业直接配送;
                    ModeComany.Append = "companytype=4";
                    break;
                //case "5":
                //    ModeComany.CompanyType = EnumCompanyType.现代医药物流企业;
                //    ModeComany.Append = "companytype=5";
                //    break;
                default: break;
            }
            switch (this.ddlSNKEY.SelectedValue)
            {

                case "":

                    break;

                case "1":
                    ModeComany.Append = " ( snkey=1 or snkey is null) ";
                    break;

                case "2":
                    ModeComany.Append = " snkey=2 ";
                    break;

                default: break;
            }
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            int totalrecord = 0;
            this.gvwCompnayist.DataSource = IBC.GetCompanyByWhere(ModeComany, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalrecord);
            this.gvwCompnayist.DataBind();
            this.AspNetPager1.RecordCount = totalrecord;
        }
        /// <summary>
        /// 
        /// </summary>
        protected string getStatus(object sender)
        {
            if (sender == null)
            {
                return "正常";
            }
            else if (sender.ToString() == "2")
            {
                return "已锁定";
            }
            return "正常";
        }
        /// <summary>
        /// 新增角色及权限,转向新页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {
            this.Response.Redirect("CompanyAdd.aspx");
        }

        /// <summary>
        /// 根据角色编号删除角色及相应的权限信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwRoleList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Del"))
            {
                Company Comy = new Company();
                string strCompanyID = e.CommandArgument.ToString();
                Comy.CompanyID = strCompanyID;
                int intRtn = IBC.DeleteCompany(Comy);
                if (intRtn == 0)
                {
                    PageError("删除失败！", "");
                }
                if (intRtn == 1)
                {
                    CompanyBind();
                    PageInfo("删除成功！", "");
                }
            }
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwCompnayist_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gvwCompnayist.EditIndex = e.NewEditIndex;
            CompanyBind();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwCompnayist_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

            GridViewRow r = gvwCompnayist.Rows[e.RowIndex];
            Company Comy = new Company();

            Comy.CompanyID = Convert.ToString(gvwCompnayist.DataKeys[e.RowIndex].Value);
            Comy.CompanyType = EnumParse.GetCompanyType(((Label)gvwCompnayist.Rows[e.RowIndex].FindControl("lblCompanyType")).Text.Trim());
            if (!string.IsNullOrEmpty(((TextBox)gvwCompnayist.Rows[e.RowIndex].FindControl("txtCompanyName")).Text.Trim()))
            {
                Comy.CompanyName = ((TextBox)gvwCompnayist.Rows[e.RowIndex].FindControl("txtCompanyName")).Text.Trim();
            }
            else
            {
                HZ.Web.WebUtil.Alert("企业名称不能为空！", this);
                ((TextBox)gvwCompnayist.Rows[e.RowIndex].FindControl("txtCompanyName")).Focus();
                return;
            }

            int flag = IBC.UpdateCompany2(Comy);
            if (flag == 1)
            {
                HZ.Web.WebUtil.Alert("更新成功！");
            }
            else if (flag == 2)
            {
                HZ.Web.WebUtil.Alert("该名称已被其他企业占用。");
            }
            else
            {
                HZ.Web.WebUtil.Alert("更新失败！");
            }
            this.gvwCompnayist.EditIndex = -1;
            CompanyBind();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwCompnayist_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gvwCompnayist.EditIndex = -1;
            CompanyBind();
        }
        /// <summary>
        /// 翻页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            this.gvwCompnayist.EditIndex = -1;
            CompanyBind();
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnQuery_Click(object sender, EventArgs e)
        {
            CompanyBind();
        }
        /// <summary>
        /// 绑定事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gvwCompnayist_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                Company c = e.Row.DataItem as Company;
                if (e.Row.FindControl("RadioButtonList1") != null)
                {
                    RadioButtonList rbl = e.Row.FindControl("RadioButtonList1") as RadioButtonList;
                    rbl.Items[0].Selected = c.CompanyType == EnumCompanyType.生产企业;
                    rbl.Items[1].Selected = c.CompanyType == EnumCompanyType.经营企业;
                    rbl.Items[2].Selected = c.CompanyType == EnumCompanyType.生产企业直接配送;
                    rbl.Items[3].Selected = c.CompanyType == EnumCompanyType.经营企业直接配送;
                    //rbl.Items[4].Selected = c.CompanyType == EnumCompanyType.现代医药物流企业;
                }

            }
        }

        protected void btnAdd_Click1(object sender, EventArgs e)
        {
            //
            Response.Redirect("~/RegCompany.aspx");
            //HZ.Web.WebUtil.RedirectByScript("CompanyAdd.aspx");
        }

        /// <summary>
        /// 返回企业名称列输出，配送企业加上查看信息链接，非配送企业直接输出名称
        /// </summary>
        /// <param name="companyId"></param>
        /// <param name="companyName"></param>
        /// <param name="companyType"></param>
        /// <param name="companyType"></param>
        /// <returns></returns>
        protected string GetCompanyRender(string companyId, string companyName, int companyType)
        {
            if (companyType == 2)
            {
                return "<a href=\"javascript:void(0)\"  title=\"查看配送企业详细信息\" onclick=\"window.open('../../CommonPage/CompanyInfo.aspx?companyid=" + companyId + "','selectCompany','width=550,height=350,resizable=0,scrollbars=0, status=0, toolbar=0, menubar=0')\" >" + companyName + "</a>";
            }
            else
            {
                return companyName;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hzbtnRandom_Click(object sender, EventArgs e)
        {

            HZ.DrugTrade.Model.Query.Company ModeComany = new HZ.DrugTrade.Model.Query.Company();

            //ModeComany.CompanyType = EnumCompanyType.医药物流企业;

            int totalrecord = 0;
            IList<Model.Company> lst = IBC.GetCompanyByWhere(ModeComany, 1, 0, out totalrecord);

            if (lst.Count > 0)
            {
                List<User> userIds = new List<User>();
                System.Data.DataTable dt = new System.Data.DataTable();
                dt.Columns.Add(new System.Data.DataColumn("UserID", Type.GetType("System.String")));
                dt.Columns.Add(new System.Data.DataColumn("UserName", Type.GetType("System.String")));
                dt.Columns.Add(new System.Data.DataColumn("UserPassword", Type.GetType("System.String")));
                Random rnd = new Random(DateTime.Now.Millisecond);
                string temp = "0";
                foreach (Model.Company item in lst)
                {
                    if (!string.IsNullOrEmpty(item.CompanyID))
                    {
                        User model = new User();
                        System.Data.DataRow dr = dt.NewRow();
                        dr["UserID"] = item.CompanyID;
                        dr["UserName"] = item.CompanyName;
                        model.UserID = item.CompanyID;
                        do
                        {

                            model.UserPassword = rnd.Next(100000, 999999).ToString();
                        }
                        while (temp == model.UserPassword);
                        temp = model.UserPassword;

                        dr["UserPassword"] = model.UserPassword;
                        userIds.Add(model);
                        dt.Rows.Add(dr);
                    }

                }
                if (userIds.Count > 0)
                {
                    if (iu.InitPassword(userIds))
                    {
                        HZ.Excel.ExcelHelper.ExportDataForWeb(dt, this.grvExcelImport);
                    }
                    else
                    {
                        HZ.Web.WebUtil.Alert("密码初始化失败！");
                    }
                }
            }
            else
            {
                HZ.Web.WebUtil.Alert("没有发现配送企业信息！");
            }
        }

        protected void HzButton1_Click(object sender, EventArgs e)
        {
            HZ.DrugTrade.Model.Query.Company ModeComany = new HZ.DrugTrade.Model.Query.Company();
            ModeComany.CompanyName = new HZ.Common.ConvertHelper(txtReturnlName.Text.Trim()).String;
            switch (DllType.SelectedItem.Value.Trim())
            {

                case "0":
                    ModeComany.CompanyType = EnumCompanyType.生产企业;
                    break;

                case "1":
                    ModeComany.CompanyType = EnumCompanyType.经营企业;
                    break;
                case "2":
                    ModeComany.CompanyType = EnumCompanyType.配送企业;
                    break;
                case "3":
                    ModeComany.CompanyType = EnumCompanyType.生产企业直接配送;
                    break;
                case "4":
                    ModeComany.CompanyType = EnumCompanyType.经营企业直接配送;
                    break;
                //case "5":
                //    ModeComany.CompanyType = EnumCompanyType.现代医药物流企业;
                //    break;
                default: break;
            }
            //AspNetPager1.PageSize = Constants.GRIDVIEW_PAGE_SIZE;
            //int totalrecord = 0;
            switch (ModeComany.CompanyType)
            {
                case Model.Enum.EnumCompanyType.生产企业:
                    //company.Append = "CompanyType = '生产企业'";
                    ModeComany.Append = "CompanyType = 0";
                    break;
                case Model.Enum.EnumCompanyType.经营企业:
                    //company.Append = "CompanyType = '经营企业'";
                    ModeComany.Append = "CompanyType = 1";
                    break;
                case Model.Enum.EnumCompanyType.配送企业:
                    //company.Append = "CompanyType = '配送企业'";
                    ModeComany.Append = "CompanyType = 2";
                    break;
                case Model.Enum.EnumCompanyType.生产企业直接配送:
                    //company.Append = "CompanyType = '配送企业'";
                    ModeComany.Append = "CompanyType = 3";
                    break;
                case Model.Enum.EnumCompanyType.经营企业直接配送:
                    //company.Append = "CompanyType = '配送企业'";
                    ModeComany.Append = "CompanyType = 4";
                    break;
                default:
                    break;
            }
            string where = HZ.DrugTrade.DAL2.DAL_Helper.GetWhereCondition<HZ.DrugTrade.Model.Query.Company>(ModeComany, true);
            //System.Data.DataTable dt = IBC.GetCompanyInfoByWhere(ModeComany, 1, 0, out totalrecord);
            string sql = string.Format(@"select  
companyid 企业编号, 
companyname 企业名称, 
nvl(telno, 0) 固定电话,
       nvl(cellno, 0) 联系人手机,
       nvl(contactperson, ' ') 联系人,
       nvl(layman, ' ') 法人代表,
       nvl(address, ' ') 公司地址,
       nvl(fax, ' ') 传真,
       --nvl(checkstatus,0) checkstatus,
       --nvl(checkperson, ' ') checkperson,
       --checkdate,
       nvl(totalfund,0) 总资产,
       nvl(fixfund,0) 固定资产,
       nvl(website, ' ') 网址,
       nvl(email, ' ') 电子邮箱,
       nvl(isgsp, 0) 是否GSP认证,
       nvl(gspcode, ' ') GSP认证编号,
       gsptime GSP认证有效期,
       nvl(remarks, ' ') 备注,
       nvl(businesscertificate,' ') 经营许可证,
        businesscertificatedate 经营许可证有效期,
       nvl(businessrange, ' ') 经营范围,
        addtime 申请时间,
       nvl(addpersonid, ' ') 添加人,
       nvl(author, ' ') 被授权人,
       nvl(authorcell, 0) 被授权人手机,
       nvl(permission, ' ') 营业执照号,
       permissiondate 营业执照有效期至,
       permissioncheckdate 营业执照年检日期,
       nvl(storehouseaddress, ' ') 仓库地址,
       nvl(adulterant, ' ') 两年内有无生产假劣药记录,
       nvl(comcode, ' ') 企业组织机构代码证号,
        comendtime 企业代码证有效期,
       nvl(postcode, ' ') 邮政编码,
       nvl(registaddress, ' ') 注册地址,
       nvl(devious, ' ') 是否有经营不良当行为,
       nvl(registerfund,0) 注册资金,case CompanyType when 0 then '生产企业' 
when 1 then '经营企业' when 2 then '配送企业' when 3 then
          '生产企业直接配送'  when 4 then
          '经营企业直接配送'  end as 企业类型,case SNKEY when '2' then '已锁定' else '正常' end as 锁定状态 
  from (select TB_CompanyInfo.*,CompanyType,SNKEY  FROM TB_CompanyInfo inner join TB_Company on TB_Company.CompanyID=TB_CompanyInfo.CompanyID ) where 1=1  {0} ", where);
            HZ.DrugTrade.BLL.ExcelHelper.ExportByWeb(HZ.Data.DbHelperFactory.Create().ExecuteTable(sql), "", "企业信息.xls");
            //HZ.Excel.ExcelHelper.ExportDataForWeb(dt, this.grvCompanyInfo);
            //ExportFile.Instance.ExportData(dt, grvCompanyInfo, this.Page);
        }
        /// <summary>
        /// 导出未选择配送关系的企业
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void HzButton2_Click(object sender, EventArgs e)
        {
            //int totalrecord = 0;
            string where =null;
            //System.Data.DataTable dt = IBC.GetCompanyInfoByWhere(ModeComany, 1, 0, out totalrecord);
            string sql = string.Format(@"select  
companyid 企业编号, 
companyname 企业名称, 
nvl(telno, 0) 固定电话,
       nvl(cellno, 0) 联系人手机,
       nvl(contactperson, ' ') 联系人,
       nvl(layman, ' ') 法人代表,
       nvl(address, ' ') 公司地址,
       nvl(fax, ' ') 传真,
       --nvl(checkstatus,0) checkstatus,
       --nvl(checkperson, ' ') checkperson,
       --checkdate,
       nvl(totalfund,0) 总资产,
       nvl(fixfund,0) 固定资产,
       nvl(website, ' ') 网址,
       nvl(email, ' ') 电子邮箱,
       nvl(isgsp, 0) 是否GSP认证,
       nvl(gspcode, ' ') GSP认证编号,
       gsptime GSP认证有效期,
       nvl(remarks, ' ') 备注,
       nvl(businesscertificate,' ') 经营许可证,
        businesscertificatedate 经营许可证有效期,
       nvl(businessrange, ' ') 经营范围,
        addtime 申请时间,
       nvl(addpersonid, ' ') 添加人,
       nvl(author, ' ') 被授权人,
       nvl(authorcell, 0) 被授权人手机,
       nvl(permission, ' ') 营业执照号,
       permissiondate 营业执照有效期至,
       permissioncheckdate 营业执照年检日期,
       nvl(storehouseaddress, ' ') 仓库地址,
       nvl(adulterant, ' ') 两年内有无生产假劣药记录,
       nvl(comcode, ' ') 企业组织机构代码证号,
        comendtime 企业代码证有效期,
       nvl(postcode, ' ') 邮政编码,
       nvl(registaddress, ' ') 注册地址,
       nvl(devious, ' ') 是否有经营不良当行为,
       nvl(registerfund,0) 注册资金,case CompanyType when 0 then '生产企业' 
when 1 then '经营企业' when 2 then '配送企业' when 3 then
          '生产企业直接配送'  when 4 then
          '经营企业直接配送'  end as 企业类型,case SNKEY when '2' then '已锁定' else '正常' end as 锁定状态 
  from (select TB_CompanyInfo.*,CompanyType,SNKEY  FROM TB_CompanyInfo inner join TB_Company on TB_Company.CompanyID=TB_CompanyInfo.CompanyID ) a 
  inner join TB_user on TB_user.userid=a.companyid  where CompanyID not in 
(SELECT CompanyID_TB FROM TB_SelectRelation) and  companyid not like 'QP%' {0} ", where);
            HZ.DrugTrade.BLL.ExcelHelper.ExportByWeb(HZ.Data.DbHelperFactory.Create().ExecuteTable(sql), "", "未选择配送关系的企业.xls");
            //System.Data.DataTable dt = IBC.GetCompanyInfoByWhere3(where,1,0,out totalrecord);

            //HZ.Excel.ExcelHelper.ExportDataForWeb(dt, grvCompanyInfo);           
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hzbtnAgree_Click(object sender, EventArgs e)
        {
            updateStatusBatch(1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void hzbtnDeny_Click(object sender, EventArgs e)
        {
            updateStatusBatch(2);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="status"></param>
        protected void updateStatusBatch(int status)
        {
            IList<Model.Company> lst = new List<Model.Company>();

            //遍历列表的所有行
            for (int _index = 0; _index < gvwCompnayist.Rows.Count; _index++)
            {
                CheckBox ckb = ((CheckBox)gvwCompnayist.Rows[_index].FindControl("checkbox1"));
                if (ckb.Checked && ckb.Enabled)
                {
                    HZ.DrugTrade.Model.Company aCompany = new HZ.DrugTrade.Model.Company();
                    aCompany.CompanyID = this.gvwCompnayist.DataKeys[_index].Values["CompanyID"].ToString();


                    if (status == 1)
                    {
                        aCompany.SNKEY = "1";
                    }
                    else
                    {
                        aCompany.SNKEY = "2";
                    }

                    lst.Add(aCompany);

                }
            }
            if (lst.Count > 0)
            {
                if (IBC.UpdateCompanySNKEY(lst, CurrentAccount.GetUser().UserID) == 1)
                {
                    //PageInfo("操作成功！", Request.RawUrl);
                    HZ.Web.WebUtil.Alert("操作成功！");
                }
                else
                {
                    //PageError("操作失败！", Request.RawUrl);
                    HZ.Web.WebUtil.Alert("操作失败！");
                }
                CompanyBind();
            }
            else
            {
                HZ.Web.WebUtil.Alert("至少选择一条记录！");
            }
        }
    }
}
